//
//  IndexTableView.m
//  tableView重用机制索引条
//
//  Created by 崔博 on 2018/6/20.
//  Copyright © 2018年 崔博. All rights reserved.
//

#define ButtonW 60

#import "IndexTableView.h"
#import "ViewReuserPool.h"
@interface IndexTableView()
{
    UIView *containerView;
    ViewReuserPool *reuserPool;
}
@end

@implementation IndexTableView

- (void)reloadData
{
    [super reloadData];
    // 懒加载
    if (containerView == nil)
    {
        containerView = [[UIView alloc]
            initWithFrame:CGRectZero];
        containerView.backgroundColor = [UIColor whiteColor];
        // 避免索引条跟着table滚动
        [self.superview insertSubview:containerView aboveSubview:self];
    }
    if (reuserPool == nil)
    {
        reuserPool = [[ViewReuserPool alloc] init];
    }
    // 标记所有试图可重用状态
    [reuserPool reset];
    
    // reload字幕条索引
    [self reloadDataIndexBar];
    
}
- (void)reloadDataIndexBar
{
    /// 获取字母索引条的显示内容
    NSArray <NSString *> *arrayTitles = nil;
    if ([self.indexedDataSource respondsToSelector:@selector(indexTitlesForIndxTable:)])
    {
        arrayTitles = [self.indexedDataSource indexTitlesForIndxTable:self];
    }
    
    // 判断索引条是否为空
    if (!arrayTitles || arrayTitles.count <= 0) {
        [containerView setHidden:YES];
        return ;
    }
    
    NSUInteger count = arrayTitles.count;
    CGFloat buttonWidth = ButtonW;
    CGFloat buttonHeight = self.frame.size.width / count;
    
    for (int i = 0; i < [arrayTitles count]; i++) {
        NSString * title = arrayTitles[i];
        
        // 从重用池 取出一个Button
        UIButton * button  = (UIButton *)[reuserPool dequeueReuserableView];
        if (button == nil) {
            button = [[UIButton alloc] initWithFrame:CGRectZero];
            button.backgroundColor = [UIColor whiteColor];
            // 注册button到重用池中
            [reuserPool addUsingView:button];
            NSLog(@"创建了一个按钮");
        }else
        {
            NSLog(@"Button 重用了");
        }
        [containerView addSubview:button];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        // 设置坐标
        button.frame = CGRectMake(0, i * buttonHeight, buttonWidth, buttonHeight);
    }
    
    containerView.hidden = NO;
    containerView.frame = CGRectMake(self.frame.origin.x + self.frame.size.width - buttonWidth,
                                     self.frame.origin.y,
                                     buttonWidth,
                                     self.frame.size.height);
    
}


@end
